package com.hanxiaozhang.threadbase1ndedition.no1synchronizedkeyword;

import java.util.ArrayList;
import java.util.List;

/**
 * 〈一句话功能简述〉<br>
 * 〈synchronized原子性〉
 * <p>
 * 去掉synchronized不能保证原子性
 *
 * @author hanxinghua
 * @create 2021/11/10
 * @since 1.0.0
 */
public class No8SynchAtomic {

    private int count = 0;

    public synchronized void add() {
        count++;
    }

    public static void main(String[] args) {

        List<Thread> list = new ArrayList<>();

        No8SynchAtomic example = new No8SynchAtomic();

        for (int i = 0; i < 10; i++) {
            Thread thread = new Thread(() -> {
                for (int j = 0; j < 10000; j++) {
                    example.add();
                }
            }, "THREAD-" + i);
            list.add(thread);
        }
        list.forEach(t -> t.start());
        list.forEach(t -> {
            try {
                t.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        System.out.println("count = " + example.count);


    }

}
